<template>
  <div class="dashboard-container">
    <!-- 页面标题 -->
    <div class="dashboard-header">
      <h1 class="dashboard-title">数据中台</h1>
      <p class="dashboard-subtitle">统一数据管理平台，助力数据驱动决策</p>
    </div>

    <!-- 统计卡片区域 -->
    <div class="stats-grid">
      <StatCard
        title="数据源"
        :value="dashboardStats?.dataSourceStats?.total || 0"
        :subtitle="`在线: ${dashboardStats?.dataSourceStats?.online || 0} | 离线: ${dashboardStats?.dataSourceStats?.offline || 0}`"
        icon="Database"
        icon-bg="#409eff"
        :trend="5.2"
        clickable
        @click="navigateTo('/dataplatform/datasource')"
      />
      
      <StatCard
        title="项目"
        :value="dashboardStats?.projectStats?.total || 0"
        :subtitle="`活跃项目: ${dashboardStats?.projectStats?.active || 0}`"
        icon="FolderOpened"
        icon-bg="#67c23a"
        :trend="2.8"
        clickable
        @click="navigateTo('/dataplatform/project')"
      />
      
      <StatCard
        title="作业"
        :value="dashboardStats?.jobStats?.total || 0"
        :subtitle="`运行中: ${dashboardStats?.jobStats?.running || 0} | 今日执行: ${dashboardStats?.jobStats?.todayExecutions || 0}`"
        icon="Operation"
        icon-bg="#e6a23c"
        :trend="-1.2"
        clickable
        @click="navigateTo('/dataplatform/job')"
      />
      
      <StatCard
        title="数据资产"
        :value="dashboardStats?.assetStats?.total || 0"
        :subtitle="`本周新增: ${dashboardStats?.assetStats?.weeklyNew || 0}`"
        icon="Files"
        icon-bg="#f56c6c"
        :trend="8.5"
        clickable
        @click="navigateTo('/dataplatform/asset')"
      />
      
      <StatCard
        title="数据服务"
        :value="dashboardStats?.apiStats?.total || 0"
        :subtitle="`今日调用: ${dashboardStats?.apiStats?.todayCalls || 0}`"
        icon="Connection"
        icon-bg="#909399"
        :trend="12.3"
        clickable
        @click="navigateTo('/dataplatform/api')"
      />
      
      <StatCard
        title="存储容量"
        :value="formatStorage(dashboardStats?.storageStats?.totalSize || 0)"
        :subtitle="`表数量: ${dashboardStats?.storageStats?.tableCount || 0}`"
        icon="Coin"
        icon-bg="#722ed1"
        :trend="3.7"
        clickable
        @click="navigateTo('/dataplatform/storage')"
      />
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <el-row :gutter="20">
        <!-- 数据源类型分布 -->
        <el-col :span="12">
          <div class="chart-card">
            <div class="chart-header">
              <h3>数据源类型分布</h3>
            </div>
            <div class="chart-content" style="height: 300px;">
              <div ref="dataSourceChart" style="width: 100%; height: 100%;"></div>
            </div>
          </div>
        </el-col>
        
        <!-- 作业执行状态 -->
        <el-col :span="12">
          <div class="chart-card">
            <div class="chart-header">
              <h3>作业执行状态</h3>
            </div>
            <div class="chart-content" style="height: 300px;">
              <div ref="jobStatusChart" style="width: 100%; height: 100%;"></div>
            </div>
          </div>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;">
        <!-- 数据资产分类 -->
        <el-col :span="12">
          <div class="chart-card">
            <div class="chart-header">
              <h3>数据资产分类</h3>
            </div>
            <div class="chart-content" style="height: 300px;">
              <div ref="assetCategoryChart" style="width: 100%; height: 100%;"></div>
            </div>
          </div>
        </el-col>
        
        <!-- 存储分布 -->
        <el-col :span="12">
          <div class="chart-card">
            <div class="chart-header">
              <h3>存储分布</h3>
            </div>
            <div class="chart-content" style="height: 300px;">
              <div ref="storageChart" style="width: 100%; height: 100%;"></div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 快速操作区域 -->
    <div class="quick-actions">
      <h3>快速操作</h3>
      <div class="action-buttons">
        <el-button type="primary" icon="Plus" @click="navigateTo('/dataplatform/datasource/add')">
          添加数据源
        </el-button>
        <el-button type="success" icon="FolderAdd" @click="navigateTo('/dataplatform/project/add')">
          创建项目
        </el-button>
        <el-button type="warning" icon="DocumentAdd" @click="navigateTo('/dataplatform/job/add')">
          新建作业
        </el-button>
        <el-button type="info" icon="Connection" @click="navigateTo('/dataplatform/api/add')">
          发布API
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import StatCard from './components/StatCard.vue'
import { getDashboardStats, type DashboardStats } from '@/api/dataplatform/dashboard'
import { ElMessage } from 'element-plus'

const router = useRouter()
const dashboardStats = ref<DashboardStats>()

// 图表引用
const dataSourceChart = ref<HTMLElement>()
const jobStatusChart = ref<HTMLElement>()
const assetCategoryChart = ref<HTMLElement>()
const storageChart = ref<HTMLElement>()

// 导航到指定页面
const navigateTo = (path: string) => {
  router.push(path)
}

// 格式化存储大小
const formatStorage = (size: number): string => {
  if (size >= 1024) {
    return (size / 1024).toFixed(1) + 'TB'
  }
  return size.toFixed(1) + 'GB'
}

// 获取统计数据
const fetchDashboardStats = async () => {
  try {
    const { data } = await getDashboardStats()
    dashboardStats.value = data
    await nextTick()
    initCharts()
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  }
}

// 初始化图表
const initCharts = () => {
  initDataSourceChart()
  initJobStatusChart()
  initAssetCategoryChart()
  initStorageChart()
}

// 数据源类型分布图表
const initDataSourceChart = () => {
  if (!dataSourceChart.value || !dashboardStats.value?.dataSourceStats?.typeDistribution) return
  
  const chart = echarts.init(dataSourceChart.value)
  const data = Object.entries(dashboardStats.value.dataSourceStats.typeDistribution).map(([name, value]) => ({
    name,
    value
  }))
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '数据源类型',
        type: 'pie',
        radius: '50%',
        data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  chart.setOption(option)
}

// 作业执行状态图表
const initJobStatusChart = () => {
  if (!jobStatusChart.value || !dashboardStats.value?.jobStats) return
  
  const chart = echarts.init(jobStatusChart.value)
  const { running, success, failed } = dashboardStats.value.jobStats
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: '5%',
      left: 'center'
    },
    series: [
      {
        name: '作业状态',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '40',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: running, name: '运行中', itemStyle: { color: '#409eff' } },
          { value: success, name: '成功', itemStyle: { color: '#67c23a' } },
          { value: failed, name: '失败', itemStyle: { color: '#f56c6c' } }
        ]
      }
    ]
  }
  
  chart.setOption(option)
}

// 数据资产分类图表
const initAssetCategoryChart = () => {
  if (!assetCategoryChart.value || !dashboardStats.value?.assetStats?.categoryDistribution) return
  
  const chart = echarts.init(assetCategoryChart.value)
  const data = Object.entries(dashboardStats.value.assetStats.categoryDistribution)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: data.map(([name]) => name),
        axisTick: {
          alignWithLabel: true
        }
      }
    ],
    yAxis: [
      {
        type: 'value'
      }
    ],
    series: [
      {
        name: '数量',
        type: 'bar',
        barWidth: '60%',
        data: data.map(([, value]) => value),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        }
      }
    ]
  }
  
  chart.setOption(option)
}

// 存储分布图表
const initStorageChart = () => {
  if (!storageChart.value || !dashboardStats.value?.storageStats?.databaseDistribution) return
  
  const chart = echarts.init(storageChart.value)
  const data = dashboardStats.value.storageStats.databaseDistribution
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    legend: {
      data: ['表数量', '存储大小(GB)']
    },
    xAxis: [
      {
        type: 'category',
        data: data.map(item => item.databaseName),
        axisPointer: {
          type: 'shadow'
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '表数量',
        min: 0,
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '存储大小',
        min: 0,
        axisLabel: {
          formatter: '{value} GB'
        }
      }
    ],
    series: [
      {
        name: '表数量',
        type: 'bar',
        data: data.map(item => item.tableCount)
      },
      {
        name: '存储大小(GB)',
        type: 'line',
        yAxisIndex: 1,
        data: data.map(item => item.storageSize)
      }
    ]
  }
  
  chart.setOption(option)
}

onMounted(() => {
  fetchDashboardStats()
})
</script>

<style scoped lang="scss">
.dashboard-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.dashboard-header {
  text-align: center;
  margin-bottom: 30px;
  
  .dashboard-title {
    font-size: 32px;
    font-weight: 600;
    color: #2c3e50;
    margin: 0 0 10px 0;
  }
  
  .dashboard-subtitle {
    font-size: 16px;
    color: #7f8c8d;
    margin: 0;
  }
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.charts-section {
  margin-bottom: 30px;
}

.chart-card {
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  
  .chart-header {
    padding: 20px 20px 0 20px;
    
    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #2c3e50;
    }
  }
  
  .chart-content {
    padding: 20px;
  }
}

.quick-actions {
  background: #ffffff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  
  h3 {
    margin: 0 0 20px 0;
    font-size: 18px;
    font-weight: 600;
    color: #2c3e50;
  }
  
  .action-buttons {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
    
    .el-button {
      flex: 1;
      min-width: 120px;
    }
  }
}

@media (max-width: 768px) {
  .dashboard-container {
    padding: 10px;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .action-buttons {
    .el-button {
      flex: 1 1 100%;
    }
  }
}
</style>
